import TauTable from '@/components/TauTable';
import { toJS } from 'mobx';
import React, { useCallback, useEffect, useState } from 'react';
import { column, orderModel } from '../stores/definitions_order.js';
import { useStore } from '@/hooks';

const subModel = orderModel.scOrder.ticketInfo[0];

function TicketTable(props) {
  const { scOrder, refundInfo = [], orderId, tickets } = props;

  const { scOrderStore: store, scTaskStore } = useStore();
  const [ticketInfo, setTicketInfo] = useState([]);

  useEffect(() => {
    const _ticket = scTaskStore.transferTickets(tickets, { id: orderId });
    setTicketInfo(_ticket);
  }, [props]);

  const reqRefundTickets = getRefundingTicket(refundInfo);

  const mapper = useCallback((row, idx) => {
    const matchRefundInfo = reqRefundTickets.find(({ ticketCode }) => ticketCode === row.ticketCode) || {};
    const isRefunding = !_.isEmpty(matchRefundInfo);
    return {
      ...row,
      id: `${row.ticketCode}-${idx}`,
      // ticketTime: scOrder?.shiftTime,
      isRefunding,
    };
  });

  // 获取正在申请退款的车票
  function getRefundingTicket(data) {
    const refundsInfo = _.cloneDeep(data) || [];
    if (refundsInfo.length <= 0) return [];

    const allTicket = refundsInfo?.reduce((res, cur) => {
      const { type, ticketRefundInfos = [] } = cur;
      if (type !== '1') {
        res.push(...ticketRefundInfos);
      }
      return res;
    }, []);
    return allTicket;
  }

  return (
    <div style={{ padding: '20px 0 20px 60px' }}>
      <TauTable
        size={'small'}
        hidePagination
        dataSource={toJS(ticketInfo.map(mapper))}
        primaryKey="ticketInfo"
        columns={[
          column('ticketCode', {
            width: 208,
            cell: (v, i, r) => {
              const { errorMsg = null, operatingTicketCode = null } = r;
              return (
                <span style={{ color: errorMsg ? 'red' : '' }}>{operatingTicketCode || v}</span>
              );
            },
          }, subModel),
          column('seats', { width: 78 }, subModel),
          column('shiftTime', { width: 140 }, subModel),
          column('state', { width: 100 }, subModel),
          column('errorMsg', { width: 138 }, subModel),
        ].concat(scOrder?.companyId === 'platform' ? [] : [
          column('operatingTakeTicketCode', {
            width: 128,
            cell: (v, i, r) => {
              return <>{v || r.ticketCode}</>;
            },
          }, subModel),
          column('operatingState', { width: 128 }, subModel)])}
      />
    </div>
  );
}
export default TicketTable;
